<template>
  <div>
    <div class="bg-white h-auto my-2 mb-2 py-2">
      <BasicForm @register="registerForm" @submit="handleSubmit" />
    </div>
    <BasicTable
      @register="registerTable"
      :data-source="tableDatas"
      size="small"
      :can-resize="true"
      :bordered="true"
      :striped="true"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddDatas"> 新增 </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '修改',
              onClick: onEditData.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteData.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <!-- 新增或修改数据使用的弹出窗口 -->
    <addOrUpdate @register="registerAddOrUpdateForm" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, onBeforeMount, onMounted, onUnmounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useRouter } from 'vue-router';
  import { EditOutlined, EyeOutlined } from '@ant-design/icons-vue';

  import {
    TSNumDataQueryConditionDto,
    TSNumDataListModel,
  } from '/@/api/demo/model/timeSeriesModel';
  import {
    getPoints,
    queryPoints,
    queryPointNumberDatas,
    savePointNumberDatas,
    addPointNumberData,
    updatePointNumberData,
    deletePointNumberDatas,
  } from '/@/api/demo/timeseries';
  import {
    timeSeriesNumberDataTableColumns,
    timeSeriesNumberDataTableQueryConditionFormSchema,
  } from './numberdata.data';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { OperationTypeEnum } from '/@/enums/appEnum';

  //引入子组件
  import addOrUpdate from './AddOrUpdate.vue';

  const [registerAddOrUpdateForm, { openModal: openAddOrUpdateForm }] = useModal();

  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { Tag } from 'ant-design-vue';
  import { Tooltip } from 'ant-design-vue';

  export default defineComponent({
    name: 'TimeSeriesNumberDataIndex',
    components: {
      EditOutlined,
      EyeOutlined,
      BasicForm,
      BasicTable,
      TableAction,
      addOrUpdate,
      Tag,
      Tooltip,
    },
    //要再setup函数中获取或使用props，需要在setup函数中获取props对象
    setup() {
      const router = useRouter();
      //定义在url中配置的点号字符串
      const pointIds = ref();
      const pointOptions = ref();
      const moduleTitle = ref('时序数据');
      //定义时序数据表格数据
      const tableDatas = ref();

      const [registerForm, { setFieldsValue, updateSchema, submit }] = useForm({
        labelWidth: 80,
        schemas: timeSeriesNumberDataTableQueryConditionFormSchema,
        // actionColOptions: {
        //   span: 24,
        // },
      });

      /**
       * 请求后台查询接口返回数据显示
       */
      const [registerTable, { reload, getForm }] = useTable({
        title: '时序数据管理',
        // api: queryPointNumberDatas,
        columns: timeSeriesNumberDataTableColumns, //表头数据
        useSearchForm: false, //单独使用查询条件表单，table中设置为false
        formConfig: {
          labelWidth: 80, //设置查询表单中label的宽度
          schemas: timeSeriesNumberDataTableQueryConditionFormSchema, // form查询表单
          showResetButton: false, //查询条件部分中是否显示重置按钮
        },
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: true,
        actionColumn: {
          width: 100,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: false, //分页
      });

      /**
       * 获取点号信息集合
       */
      function getPointsInfo() {
        //如果有在url中指定点号ID字符串则获取对应点号ID的信息，如果没有指定获取所有点号信息
        let options = [];
        //设置所有下拉项均为选中
        let selectIds = [];
        console.log('pointIds.value= ' + pointIds.value);
        if (!pointIds.value) {
          //没有指定点号ID字符串，获取所有点号信息
          console.log('getPoints query all');
          queryPoints().then((res) => {
            console.log('getPoints res', res);
            if (res != null && res.length > 0x0) {
              //查询所有点号时，默认选择第1个点号
              selectIds.push(res[0x0].pointid);

              res.forEach((item) => {
                //将点号的全部信息均进行记录，并传递到数据新增/编辑表单中
                let optionItem = item;
                optionItem.value = item.pointid;
                optionItem.label = item.pointname;
                // options.push({
                //   value: item.pointid,
                //   label: item.pointname,
                // });
                options.push(optionItem);
              });
            }

            pointOptions.value = options;

            updateSchema({
              field: 'pointids',
              componentProps: {
                options: options,
                // value: selectIds,//vben中的FormSchema不能直接使用antd中的组件属性
              },
            });
            //设置点号下拉框选中值
            setFieldsValue({ pointids: selectIds });
            //调用一次查询条件表单的提交事件，刷新数据表格
            submit();
          });
        } else {
          console.log('getPoints ', pointIds.value);
          getPoints(pointIds.value).then((res) => {
            console.log('getPoints res', res);
            if (res != null && res.length > 0x0) {
              res.forEach((item) => {
                options.push({
                  value: item.pointid,
                  label: item.pointname,
                });
                selectIds.push(item.pointid);
              });
            }

            pointOptions.value = options;

            updateSchema({
              field: 'pointids',
              componentProps: {
                options: options,
                // value: selectIds,//vben中的FormSchema不能直接使用antd中的组件属性
              },
            });
            //设置点号下拉框选中值
            setFieldsValue({ pointids: selectIds });
            //调用一次查询条件表单的提交事件，刷新数据表格
            submit();
          });
        }

        //前面的查询后台接口未返回处理结束，此处不是按顺序执行的
        console.log('getPoints result options', options);
      }

      /**
       * 表单提交按钮事件
       */
      function handleSubmit(values: any) {
        console.log(values);
        let date = values.beginEndtm;
        console.log('date', date);
        let beginDate;
        let endDate;
        for (let i = 0; i < date.length; i++) {
          beginDate = date[0];
          endDate = date[1];
        }

        //先对时序数据表格数据赋值为空
        tableDatas.value = [];
        //时序数据查询条件定义和赋值
        let queryConditionDto: TSNumDataQueryConditionDto = {
          begintm: beginDate,
          endtm: endDate,
          pointids: values.pointids,
        };
        queryPointNumberDatas(queryConditionDto).then((res) => {
          if (res != null && res.datas != null && res.datas.length > 0x0) {
            //查询返回结果中datas为数据集合，points为点号信息集合，需要从点号信息集合中获取对应的点号名称
            res.datas.forEach((item) => {
              //根据当前数据的点号ID获取点号名称信息
              let pointid = item.pointid;

              if (res.points != null && res.points.length > 0x0) {
                const point = res.points.find((p) => p.pointid === pointid);
                if (point != null && point.pointname) {
                  item.pointname = point.pointname;
                  item.unit = point.unit;
                }
              }

              tableDatas.value.push(item);
            });
            // console.log('queryPointNumberDatas datas ', datas);
          }
        });
      }

      /**
       * 打开新增数据窗口
       */
      function onAddDatas() {
        //使用props传递数据至子组件，在data参数中指定
        let propsData: QcUnifyTransToChildProps = {
          moduleName: moduleTitle.value,
          operateType: OperationTypeEnum.ADD,
          options: pointOptions.value, //将点号集合传递给比新增或编辑表单用于界面中进行显示
        };

        openAddOrUpdateForm(true, propsData);
      }

      /**
       * 打开修改数据窗口
       * @param record 行数据
       */
      function onEditData(record: Recordable) {
        //使用props传递数据至子组件，在data参数中指定
        let propsData: QcUnifyTransToChildProps = {
          moduleName: moduleTitle.value,
          operateType: OperationTypeEnum.EDIT,
          // dataId: record.id,
          data: record, //将当前行数据传递给编辑表单界面
          options: pointOptions.value, //将点号集合传递给比新增或编辑表单用于界面中进行显示
        };
        openAddOrUpdateForm(true, propsData);
      }

      /**
       * 删除
       */
      function onDeleteData(record: Recordable) {
        //删除点号数据时需要点号ID和数据时标，传入整行数据对象
        //接口支持批量删除，需要传入集合对象
        let deleteDatas: TSNumDataListModel = [];
        deleteDatas.push(record);
        deletePointNumberDatas(deleteDatas).then((res) => {
          if (!res) {
            createMessage.success('删除成功。', 2);
            afterSuccess();
          } else {
            //删除接口返回有错误提示信息
            createMessage.error(res);
          }
        });
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        submit();
      }

      onBeforeMount(() => {
        console.log('TimeSeries NumberData Index.vue onBeforeMount');
        //从router.fullPath中获取传入的参数，并对空元素进行去除
        let urlParamIds = ''; //固定取url中以斜线/分隔的第3个有效元素
        let fullPathArray = router.currentRoute.value.fullPath.split('/');
        if (fullPathArray != undefined && fullPathArray != null && fullPathArray.length > 0x0) {
          let notEmptyPathArray = fullPathArray.filter((str) => str.length > 0x0);
          if (notEmptyPathArray.length > 0x2) urlParamIds = notEmptyPathArray[0x2];
        }

        console.log('TimeSeries NumberData Index.vue onBeforeMount get urlParamIds=' + urlParamIds);
        pointIds.value = urlParamIds;
      });
      onMounted(() => {
        //必须要在onMounted才可以使用getForm，在onBeforeMount中无法获取到getForm
        //如果有指定点号ID字符串，调用后台接口获取点号ID和名称信息用于绑定到下拉列表中
        getPointsInfo();
      });
      onUnmounted(() => {
        console.log('ParamValue Index.vue onUnmounted');
      });

      return {
        pointIds,
        pointOptions,
        registerForm,
        handleSubmit,
        registerTable,
        registerAddOrUpdateForm,
        afterSuccess,
        tableDatas,
        onAddDatas,
        onEditData,
        onDeleteData,
      };
    },
  });
</script>
